package com.uwo.house.controller;

import com.uwo.house.advice.Code;
import com.uwo.house.beans.User;
import com.uwo.house.beans.request.AddStaffReq;
import com.uwo.house.beans.request.ClientModifyReq;
import com.uwo.house.beans.request.ModifyStaffReq;
import com.uwo.house.beans.response.StaffUserResp;
import com.uwo.house.beans.response.UserResp;
import com.uwo.house.config.JWTAuthenticationToken;
import com.uwo.house.exception.ControllerException;
import com.uwo.house.kits.CacheKits;
import com.uwo.house.kits.EncryptKits;
import com.uwo.house.service.IUserService;
import com.uwo.house.util.DateUtils;
import com.uwo.house.util.UtilReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by yanhao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @ResponseBody
    @RequestMapping(value = "/info")
    public Object index(@RequestHeader(value = "Authorization") String token) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        User user = jwtToken.getUser();
        UserResp userResp = userService.getUserByUserName(user.getUsername());
        User u = userService.selectByUnionid(user.getUsername());
        Map<String, Object> result = new HashMap();
        result.put("code", 200);
        result.put("user", userResp);
        result.put("member", u.getMember());
        return result;
    }

    /**
     * 忘记密码
     *
     * @param mobile
     * @param sms
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forgot", method = RequestMethod.PUT)
    public Object forgot(
            @RequestParam(value = "mobile") String mobile,
            @RequestParam(value = "sms") String sms
    ) {
        User user = userService.selectByUsername(mobile);
        if (!mobile.equals(user.getMobile())) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "手机号不正确");
        }
        String smsMobile = (String) CacheKits.get(sms);
        if (mobile.equals(smsMobile)) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "验证码正确");
        } else {
            return UtilReturn.resErrorMap("验证码错误！", UtilReturn.ERROR_CODE);
        }
    }

    /**
     * 忘记密码-修改密码
     * @param mobile
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forgot/passwordmodify", method = RequestMethod.PUT)
    public Map modifyPassword(@RequestParam(value = "mobile") String mobile,
                              @RequestParam(value = "password") String password) {
        User user = userService.selectByUsername(mobile);
        boolean isTrue = userService.modifyPassword(user, password);
        if (isTrue == true) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "重置成功");
        }
        return UtilReturn.resErrorMap("重置失败！", UtilReturn.ERROR_CODE);
    }

    /**
     * 更换密码
     * @param token
     * @param oldPassword
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/passwordmodify", method = RequestMethod.PUT)
    public Object pwd(
            @RequestHeader(value = "Authorization") String token,
            @RequestParam(value = "oldPassword") String oldPassword,
            @RequestParam(value = "password") String password
    ) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        User user = jwtToken.getUser();
        String passwordToModify = EncryptKits.Md5(EncryptKits.Md5(oldPassword).toLowerCase() + user.getSalt()).toLowerCase();
        if (!passwordToModify.equals(user.getPassword())){
            return UtilReturn.resErrorMap("原密码不正确！", UtilReturn.ERROR_CODE);
        }
        boolean isTrue = userService.modifyPassword(user, password);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", (isTrue) ? 200 : 503);
        return result;
    }

    /**
     * 更换手机号
     * @param token
     * @param mobile
     * @param sms
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/{mobile}/{sms}/modify", method = RequestMethod.GET)
    public Object mobile(
            @RequestHeader(value = "Authorization") String token,
            @PathVariable String mobile,
            @PathVariable String sms
    ) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        if (!CacheKits.has(sms))
            new ControllerException(Code.VERIFY_CODE_ERROR);
        String smsMobile = (String) CacheKits.get(sms);
        if (!mobile.equalsIgnoreCase(smsMobile))
            new ControllerException(Code.MOBILE_VERIFICATION_FAILED);
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        //Member member = jwtToken.getUser().getMember();
        User user = jwtToken.getUser();
        user.setMobile(mobile);
        boolean isTrue = userService.modifyMobile(jwtToken.getUser(), jwtToken.getUser().getMobile());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", (isTrue) ? 200 : 503);
        return result;
    }

    /**
     * 后台查询用户账号列表
     *
     * @param userName
     * @param dateFromStr
     * @param dateToStr
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Map getUserList(@RequestParam(value = "userName", required = false) String userName,
                           @RequestParam(value = "dateFromStr", required = false) String dateFromStr,
                           @RequestParam(value = "dateToStr", required = false) String dateToStr) {
        Date dateFrom = DateUtils.getDate(dateFromStr);
        Date dateTo = DateUtils.getDate(dateToStr);
        List<UserResp> list = this.userService.getUsers(userName, dateFrom, dateTo);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, list);
    }

    /**
     * 后台管理-删除账号
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Map deleteUser(@RequestParam(value = "id") String id) {
        int result = this.userService.deleteUser(id);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "删除成功");
        }
        return UtilReturn.resErrorMap("删除失败", UtilReturn.ERROR_CODE);
    }

    /**
     * 员工账号查询
     *
     * @param roleId
     * @param userName
     * @param name
     * @param address
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff/list", method = RequestMethod.GET)
    public Map getStaffList(@RequestParam("roleId") int roleId,
                            @RequestParam(value = "userName", required = false) String userName,
                            @RequestParam(value = "name", required = false) String name,
                            @RequestParam(value = "address", required = false) String address,
                            @RequestParam(value = "supplyClass", required = false) String supplyClass) {
        List<StaffUserResp> list = this.userService.getStaffList(roleId, userName, name, address,supplyClass);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, list);
    }

    /**
     * 修改员工账号信息
     *
     * @param modifyStaffReq
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff/modify", method = RequestMethod.PUT)
    public Map modifyStaffUser(@RequestBody ModifyStaffReq modifyStaffReq) {
//        User user = userService.getUserByMobile(modifyStaffReq.getId());
        User user = userService.selectByUsername(modifyStaffReq.getId());
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(modifyStaffReq.getPassword())).toLowerCase() + user.getSalt()).toLowerCase();
        modifyStaffReq.setPassword(pwd);
        int result = this.userService.modifyStaffUser(modifyStaffReq);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "修改成功");
        }
        return UtilReturn.resErrorMap("修改失败", UtilReturn.ERROR_CODE);
    }

    /**
     * 添加员工账号
     *
     * @param addStaffReq
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff/add", method = RequestMethod.POST)
    private Map addStaffUser(@RequestBody AddStaffReq addStaffReq) {
        addStaffReq.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        addStaffReq.setMid(UUID.randomUUID().toString().replaceAll("-", ""));
        addStaffReq.setSalt(EncryptKits.generatePassword());
        String pwd = EncryptKits.Md5(EncryptKits.Md5(new String(addStaffReq.getPassword())).toLowerCase() + addStaffReq.getSalt()).toLowerCase();
        addStaffReq.setPassword(pwd);
        int result = this.userService.addStaffUser(addStaffReq);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "添加成功");
        }
        return UtilReturn.resErrorMap("添加失败", UtilReturn.ERROR_CODE);
    }

    /**
     * 验证手机号是否存在
     *
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkmobile", method = RequestMethod.GET)
    public Map checkMobile(@RequestParam("mobile") String mobile) {
        int count = this.userService.checkMobile(mobile);
        if (count == 0) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "手机号码不存在");
        }
        return UtilReturn.resErrorMap("手机号码已存在", UtilReturn.ERROR_CODE);
    }

    /**
     * 登录用户信息
     *
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff/info")
    public Map getLoginUserInfo(@RequestHeader(value = "Authorization") String token) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        String userId = jwtToken.getUser().getId();
        StaffUserResp staffUserResp = userService.getStaffUserInfo(userId);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, staffUserResp);
    }

    /**
     * 客户中心-用户修改信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/client/modify")
    public Map modifyClientInfo(@RequestBody ClientModifyReq clientModifyReq) {
        int result = userService.modifyClientInfo(clientModifyReq);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "保存成功");
        }
        return UtilReturn.resErrorMap("保存失败", UtilReturn.ERROR_CODE);
    }

    /**
     * 更换密码
     *
     * @param token
     * @param oldPassword
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff/passwordmodify", method = RequestMethod.PUT)
    public Map modifyStaffPwd(
            @RequestHeader(value = "Authorization") String token,
            @RequestParam(value = "oldPassword") String oldPassword,
            @RequestParam(value = "password") String password
    ) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        User user = jwtToken.getUser();
        String passwordToModify = EncryptKits.Md5(EncryptKits.Md5(oldPassword).toLowerCase() + user.getSalt()).toLowerCase();
        if (!passwordToModify.equals(user.getPassword())) {
            return UtilReturn.resErrorMap("原密码不正确！", UtilReturn.ERROR_CODE);
        }
        int result = userService.modifyStaffPassword(user, password);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "修改成功");
        }
        return UtilReturn.resErrorMap("修改失败", UtilReturn.ERROR_CODE);
    }

    /**
     * 修改支付宝账号
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/aliaccount/modify")
    public Map modifyAliAccount(String aliAccount,String userId) {
        int result = userService.modifyAliAccount(aliAccount,userId);
        if (result == 1) {
            return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "保存成功");
        }
        return UtilReturn.resErrorMap("保存失败", UtilReturn.ERROR_CODE);
    }

}
